<template>
  <div class="articles-container">
    <div class="articles-header">
      <h1>文章列表</h1>
      <el-button type="primary" @click="createArticle" v-if="isLoggedIn">发布新文章</el-button>
    </div>
    
    <div v-if="loading" class="loading">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="error" class="error-message">
      {{ error }}
    </div>
    
    <div v-else>
      <div v-if="articles.length === 0" class="no-articles">
        暂无文章，快来发布第一篇吧！
      </div>
      
      <el-card v-for="article in articles" :key="article.id" class="article-card" shadow="hover">
        <div class="article-title" @click="viewArticle(article.id)">
          <h3>{{ article.title }}</h3>
        </div>
        <div class="article-meta">
          <span>作者: {{ article.author ? article.author.username : '未知' }}</span>
          <span>发布时间: {{ formatDate(article.createdAt) }}</span>
        </div>
        <div class="article-summary">
          {{ getArticleSummary(article.content) }}
        </div>
        <div class="article-actions">
          <el-button type="text" @click="viewArticle(article.id)">阅读全文</el-button>
          <div v-if="isAuthor(article)">
            <el-button type="text" @click="editArticle(article.id)">编辑</el-button>
            <el-button type="text" @click="confirmDelete(article.id)">删除</el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Articles',
  data() {
    return {
      articles: [],
      loading: true,
      error: null,
      currentUser: null
    }
  },
  computed: {
    isLoggedIn() {
      return !!this.currentUser;
    }
  },
  created() {
    // 获取当前登录用户信息
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      this.currentUser = JSON.parse(userInfo);
    }
    
    this.fetchArticles();
  },
  methods: {
    fetchArticles() {
      this.loading = true;
      this.$axios.get('/api/posts')
        .then(response => {
          this.articles = response.data;
          this.loading = false;
        })
        .catch(error => {
          console.error('获取文章列表失败:', error);
          this.error = '获取文章列表失败，请稍后重试';
          this.loading = false;
        });
    },
    formatDate(dateString) {
      if (!dateString) return '未知时间';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },
    getArticleSummary(content) {
      if (!content) return '';
      return content.length > 100 ? content.substring(0, 100) + '...' : content;
    },
    viewArticle(articleId) {
      this.$router.push(`/posts/${articleId}`);
    },
    createArticle() {
      this.$router.push('/posts/create');
    },
    editArticle(articleId) {
      this.$router.push(`/posts/edit/${articleId}`);
    },
    isAuthor(article) {
      return this.currentUser && article.author && this.currentUser.id === article.author.id;
    },
    confirmDelete(articleId) {
      this.$confirm('确定要删除这篇文章吗？此操作不可逆', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteArticle(articleId);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteArticle(articleId) {
      this.$axios.delete(`/api/posts/${articleId}`)
        .then(() => {
          this.$message({
            type: 'success',
            message: '文章删除成功'
          });
          // 重新获取文章列表
          this.fetchArticles();
        })
        .catch(error => {
          console.error('删除文章失败:', error);
          this.$message({
            type: 'error',
            message: '删除文章失败，请稍后重试'
          });
        });
    }
  }
}
</script>

<style scoped>
.articles-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.articles-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.article-card {
  margin-bottom: 20px;
}

.article-title {
  cursor: pointer;
}

.article-title h3 {
  margin: 0;
  color: var(--primary-color);
}

.article-meta {
  margin: 10px 0;
  color: #909399;
  font-size: 14px;
}

.article-meta span {
  margin-right: 15px;
}

.article-summary {
  color: var(--text-regular);
  margin-bottom: 10px;
  line-height: 1.5;
}

.article-actions {
  display: flex;
  justify-content: space-between;
}

.loading, .error-message, .no-articles {
  padding: 20px;
  text-align: center;
}

.error-message {
  color: var(--danger-color);
}

.no-articles {
  color: var(--text-secondary);
  font-style: italic;
}
</style>